package likouJava;

import java.util.Stack;

public class 字符串解码 {
    public String decodeString(String s) {
        Stack<Integer> countStack = new Stack<>();
        Stack<StringBuilder> strStack = new Stack<>();
        StringBuilder currentStr = new StringBuilder();
        int k = 0;

        for (char c : s.toCharArray()){
            if (Character.isDigit(c)){
                k = k * 10 + (c - '0');
            }else if (c == '['){
                countStack.push(k);
                strStack.push(currentStr);
                //重置
                k = 0;
                currentStr = new StringBuilder();
            } else if (c == ']') {
                // 出栈拼接
                int repeatCount = countStack.pop();
                StringBuilder decodePart = currentStr;
                currentStr = strStack.pop();

                while (repeatCount -- > 0){
                    currentStr.append(decodePart);
                }
            }else {
                currentStr.append(c);
            }
        }
        return currentStr.toString();
    }

    // 测试
    public static void main(String[] args) {
        字符串解码 solution = new 字符串解码();
        System.out.println(solution.decodeString("3[a]2[bc]"));      // aaabcbc
        System.out.println(solution.decodeString("3[a2[c]]"));       // accaccacc
        System.out.println(solution.decodeString("2[abc]3[cd]ef"));  // abcabccdcdcdef
        System.out.println(solution.decodeString("abc3[cd]xyz"));    // abccdcdcdxyz
    }

}
